package com.yygo.util;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * 通过手机号码,获得该号码的归属地
 *
 * @author Administrator
 *
 */
public class MobileFromUtil {

    /**
     * 测试
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        System.out.println(getMobileAddress("13407229528"));
    }
    public static String gb2312ToUtf8(String str) {

        String urlEncode = "" ;

        try {

            urlEncode = URLEncoder.encode(str, "UTF-8");

        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();

        }

        return urlEncode;

    }

    public static boolean isValid(String mobile) {
        return StringUtil.isBlankOrNull(mobile)? false: mobile.matches("^(13|15|18)\\d{9}$") || mobile.matches("^(013|015|018)\\d{9}$");
    }

    public static String getMobileAddress(String mobile)
    {
        String address = "";
        try
        {
            mobile = mobile.trim();
            if (isValid(mobile)) //以13，15，18开头，后面九位全为数字
            {
                String url = "http://www.ip138.com:8080/search.asp?action=mobile&mobile=" + mobile;
                URLConnection connection = (URLConnection) new URL(url).openConnection();
                connection.setDoOutput(true);
                InputStream os = connection.getInputStream();
                Thread.sleep(100);
                int length = os.available();
                byte[] buff = new byte[length];
                os.read(buff);
                String s = new String(buff, "gbk");
                // <TD width="138" align="center">卡号归属地</TD><td align="center" class=tdc2><!-- <td></td> -->湖北&nbsp;江汉（天门/仙桃/潜江）区</TD>
                String markStr = "卡号归属地</TD>";
                int len = s.lastIndexOf(markStr);
                int lastIndex = s.indexOf("</TD>", len+markStr.length());
                s = s.substring(len+markStr.length(), lastIndex+5);
                System.out.println("mobile: " + mobile);
                System.out.println("value: " + s);
                s = s.replaceAll("<(TD|td) .*>(.*)</(td|TD)>", "$2");
                address = s.replace("&nbsp;", "");
                //address = address.replace("d> -->", "");
                //address = address.replace(" -->", "");
                address = address.replace("-->", "");
                address = address.trim();
                s = null;
                buff = null;
                os.close();
                connection = null;
            }
        }
        catch(Exception e)
        {
            address = "unknown";
            System.out.println("手机所属地查询失败====================");
        }
        try {
            address = gb2312ToUtf8(address);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return address;
    }
}